const api = require('../../utils/api')
const locationService = require('../../utils/location')
const qrCodeService = require('../../utils/qrcode')
const app = getApp()
const utils = require('../../utils/util')

Page({
  data: {
    currentLocation: '正在获取位置...',
    searchKeyword: '',
    loading: true,
    stores: [],
    selectedService: 'delivery',
    selectedCategory: null,
    recommendedFood: [],
    categories: [],
    banners: [],
    userInfo: null
  },

  onLoad() {
    console.log('首页加载');
    this.initPage();
  },

  onShow() {
    console.log('首页显示');
    this.loadUserLocation();
    this.refreshCartStatus();
  },

  onPullDownRefresh() {
    console.log('下拉刷新');
    this.refreshAll();
    wx.stopPullDownRefresh();
  },

  onReachBottom() {
    console.log('触底加载更多');
    this.loadMoreStores();
  },

  // === 🎯 页面初始化 ===
  async initPage() {
    try {
      // 显示加载状态
      this.setData({ loading: true });
      
      // 并行执行初始化任务
      await Promise.all([
        this.loadUserLocation(),
        this.loadBanners(),
        this.loadCategories(),
        this.loadRecommendedFood(),
        this.loadStores(),
        this.getUserInfo()
      ]);
      
    } catch (error) {
      console.error('页面初始化失败:', error);
      this.showError('页面加载失败，请重试');
    } finally {
      this.setData({ loading: false });
    }
  },

  // === 📍 位置相关 ===
  async loadUserLocation() {
    try {
      const location = await this.getLocation();
      const address = await this.reverseGeocode(location);
      
      this.setData({
        currentLocation: address || '未知位置'
      });
      
      console.log('当前位置:', address);
    } catch (error) {
      console.error('获取位置失败:', error);
      this.setData({
        currentLocation: '定位失败，点击重试'
      });
    }
  },

  getLocation() {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        success: resolve,
        fail: reject
      });
    });
  },

  async reverseGeocode(location) {
    // 这里应该调用地图API进行逆地理编码
    // 暂时返回模拟地址
    return '北京市朝阳区三里屯街道';
  },

  // === 🔍 搜索功能 ===
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  async onSearch() {
    const keyword = this.data.searchKeyword.trim();
    
    if (!keyword) {
      this.showToast('请输入搜索关键词');
      return;
    }

    // 触觉反馈
    wx.vibrateShort();
    
    console.log('搜索:', keyword);
    
    try {
      this.setData({ loading: true });
      
      // 模拟搜索API调用
      const searchResults = await this.searchStores(keyword);
      
      this.setData({
        stores: searchResults,
        loading: false
      });
      
      this.showToast(`找到 ${searchResults.length} 个结果`);
      
    } catch (error) {
      console.error('搜索失败:', error);
      this.showError('搜索失败，请重试');
      this.setData({ loading: false });
    }
  },

  async searchStores(keyword) {
    // 模拟搜索API
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockResults = this.getMockStores().filter(store => 
          store.name.includes(keyword) || 
          store.tags.some(tag => tag.includes(keyword))
        );
        resolve(mockResults);
      }, 1000);
    });
  },

  // === 🚀 服务选择 ===
  onSelectService(e) {
    const serviceType = e.currentTarget.dataset.type;
    
    // 触觉反馈
    wx.vibrateShort();
    
    this.setData({
      selectedService: serviceType
    });

    console.log('选择服务类型:', serviceType);

    // 根据服务类型显示不同的提示和操作
    switch (serviceType) {
      case 'delivery':
        this.showServiceInfo('外卖配送', '为您筛选支持外卖配送的商家', '#4CAF50');
        this.filterStoresByService('delivery');
        break;
      case 'pickup':
        this.showServiceInfo('到店自取', '为您筛选支持到店自取的商家', '#2196F3');
        this.filterStoresByService('pickup');
        break;
      case 'dine-in':
        this.showServiceInfo('堂食预订', '为您筛选支持堂食预订的商家', '#FF9800');
        this.filterStoresByService('dine-in');
        break;
      case 'group-buy':
        this.showServiceInfo('团购优惠', '为您筛选有团购优惠的商家', '#E91E63');
        this.filterStoresByService('group-buy');
        break;
      default:
        this.showToast('服务类型未知');
    }
  },

  showServiceInfo(title, message, color) {
    wx.showModal({
      title: `已选择：${title}`,
      content: message,
      showCancel: false,
      confirmText: '知道了',
      confirmColor: color,
      success: () => {
        console.log(`用户确认选择了${title}服务`);
      }
    });
  },

  async filterStoresByService(serviceType) {
    try {
      this.setData({ loading: true });
      
      // 模拟根据服务类型筛选商家
      const filteredStores = await this.getStoresByService(serviceType);
      
      this.setData({
        stores: filteredStores,
        loading: false
      });
      
      if (filteredStores.length === 0) {
        this.showToast('暂无支持该服务的商家');
      }
      
    } catch (error) {
      console.error('筛选商家失败:', error);
      this.showError('筛选失败，请重试');
      this.setData({ loading: false });
    }
  },

  async getStoresByService(serviceType) {
    // 模拟API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        const allStores = this.getMockStores();
        const filtered = allStores.filter(store => 
          store.services && store.services.includes(serviceType)
        );
        resolve(filtered);
      }, 800);
    });
  },

  // === 🏪 商家相关 ===
  async loadStores() {
    try {
      const stores = await this.fetchStores();
      this.setData({
        stores: stores
      });
      console.log('加载商家列表成功:', stores.length);
    } catch (error) {
      console.error('加载商家失败:', error);
      this.showError('加载商家失败');
    }
  },

  async fetchStores() {
    // 模拟API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(this.getMockStores());
      }, 1500);
    });
  },

  getMockStores() {
    return [
      {
        id: 1,
        name: '麦当劳',
        image: '/images/stores/mcdonald.jpg',
        rating: 4.8,
        reviewCount: 1234,
        tags: ['汉堡', '快餐', '美式'],
        distanceText: '0.5km',
        deliveryTimeText: '25-35分钟',
        deliveryFee: 3,
        isOpen: true,
        services: ['delivery', 'pickup'],
        features: ['新店优惠', '满减活动']
      },
      {
        id: 2,
        name: '海底捞火锅',
        image: '/images/stores/haidilao.jpg',
        rating: 4.6,
        reviewCount: 856,
        tags: ['火锅', '川菜', '辣味'],
        distanceText: '0.8km',
        deliveryTimeText: '30-40分钟',
        deliveryFee: 4,
        isOpen: true,
        services: ['delivery', 'dine-in'],
        features: ['招牌推荐', '学生优惠']
      },
      {
        id: 3,
        name: '星巴克咖啡',
        image: '/images/stores/starbucks.jpg',
        rating: 4.9,
        reviewCount: 567,
        tags: ['咖啡', '轻食', '饮品'],
        distanceText: '1.2km',
        deliveryTimeText: '40-50分钟',
        deliveryFee: 6,
        isOpen: true,
        services: ['delivery', 'pickup', 'dine-in'],
        features: ['精品推荐', '会员专享']
      },
      {
        id: 4,
        name: '必胜客',
        image: '/images/stores/pizza_hut.jpg',
        rating: 4.7,
        reviewCount: 432,
        tags: ['披萨', '意式', '西餐'],
        distanceText: '0.3km',
        deliveryTimeText: '20-30分钟',
        deliveryFee: 2,
        isOpen: false,
        services: ['pickup', 'group-buy'],
        features: ['团购特惠', '生日定制']
      }
    ];
  },

  async loadMoreStores() {
    // 模拟加载更多
    console.log('加载更多商家...');
    // 这里可以实现分页加载逻辑
  },

  // === 🎯 快捷操作 ===
  goToOrders() {
    wx.vibrateShort();
    console.log('跳转到我的订单');
    wx.navigateTo({
      url: '/pages/order/order',
      fail: () => {
        this.showToast('订单页面开发中...');
      }
    });
  },

  goToFavorites() {
    wx.vibrateShort();
    console.log('跳转到我的收藏');
    wx.navigateTo({
      url: '/pages/favorite/favorite',
      success: () => {
        console.log('跳转到收藏页面成功');
      },
      fail: (error) => {
        console.error('跳转到收藏页面失败:', error);
        this.showToast('页面跳转失败，请重试');
      }
    });
  },

  goToCoupons() {
    wx.vibrateShort();
    console.log('跳转到优惠券');
    wx.navigateTo({
      url: '/pages/coupon/coupon',
      success: () => {
        console.log('跳转到优惠券页面成功');
      },
      fail: (error) => {
        console.error('跳转到优惠券页面失败:', error);
        this.showToast('页面跳转失败，请重试');
      }
    });
  },

  goToHelp() {
    wx.vibrateShort();
    console.log('跳转到帮助中心');
    wx.navigateTo({
      url: '/pages/help/help',
      success: () => {
        console.log('跳转到帮助中心成功');
      },
      fail: (error) => {
        console.error('跳转到帮助中心失败:', error);
        this.showToast('页面跳转失败，请重试');
      }
    });
  },

  // === 🏪 商家操作 ===
  goToStore(e) {
    const storeId = e.currentTarget.dataset.id;
    
    // 触觉反馈
    wx.vibrateShort();
    
    console.log('跳转到商家详情:', storeId);
    
    wx.navigateTo({
      url: `/pages/store-detail/store-detail?id=${storeId}`,
      fail: (error) => {
        console.error('跳转失败:', error);
        this.showToast('页面跳转失败');
      }
    });
  },

  viewMoreStores() {
    wx.vibrateShort();
    console.log('查看更多商家');
    this.showToast('更多商家功能开发中...');
  },

  // === 📍 位置操作 ===
  chooseLocation() {
    wx.vibrateShort();
    
    wx.chooseLocation({
      success: (res) => {
        console.log('选择位置成功:', res);
        this.setData({
          currentLocation: res.name || res.address || '未知位置'
        });
        
        // 重新加载附近商家
        this.refreshData();
        this.showToast('位置更新成功');
      },
      fail: (error) => {
        console.error('选择位置失败:', error);
        this.showToast('位置选择失败');
      }
    });
  },

  // === 🔄 数据刷新 ===
  async refreshData() {
    try {
      this.setData({ loading: true });
      
      await Promise.all([
        this.loadUserLocation(),
        this.loadStores()
      ]);
      
      this.showToast('刷新成功');
      
    } catch (error) {
      console.error('刷新失败:', error);
      this.showError('刷新失败，请重试');
    } finally {
      this.setData({ loading: false });
    }
  },

  // === 👤 用户信息 ===
  async getUserInfo() {
    try {
      const userInfo = await this.fetchUserInfo();
      this.setData({ userInfo });
      console.log('获取用户信息成功');
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
  },

  async fetchUserInfo() {
    // 模拟获取用户信息
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          nickname: '美食爱好者',
          avatar: '/images/default-avatar.png'
        });
      }, 500);
    });
  },

  // === 🛠️ 工具方法 ===
  showToast(title, icon = 'none') {
    wx.showToast({
      title,
      icon,
      duration: 2000
    });
  },

  showError(message) {
    wx.showModal({
      title: '提示',
      content: message,
      showCancel: false,
      confirmText: '知道了',
      confirmColor: '#FF6B47'
    });
  },

  // 刷新购物车状态
  refreshCartStatus() {
    const app = getApp();
    if (app && app.globalData && app.globalData.cart) {
      const cartCount = app.globalData.cart.reduce((total, item) => total + item.quantity, 0);
      if (cartCount > 0) {
        wx.setTabBarBadge({
          index: 2, // 购物车的tabBar索引
          text: cartCount.toString()
        }).catch(err => console.error('设置购物车角标失败:', err));
      } else {
        wx.removeTabBarBadge({
          index: 2
        }).catch(err => console.error('移除购物车角标失败:', err));
      }
    }
  },

  // 刷新所有数据
  refreshAll() {
    this.setData({ loading: true });
    Promise.all([
      this.loadUserLocation(),
      this.loadBanners(),
      this.loadCategories(),
      this.loadRecommendedFood(),
      this.loadStores(),
      this.getUserInfo()
    ]).finally(() => {
      this.setData({ loading: false });
    });
  },

  // === 🚨 测试函数 ===
  testGoToOrder() {
    wx.vibrateShort();
    console.log('测试：直接跳转到订单页面');
    
    // 模拟购物车数据
    const app = getApp();
    app.globalData.cart = [
      {
        storeId: 1,
        productId: 1,
        name: '巨无霸套餐',
        price: 35.5,
        quantity: 1,
        image: '/images/products/bigmac.jpg',
        specifications: ['大份薯条', '可乐']
      },
      {
        storeId: 1,
        productId: 2,
        name: '麦辣鸡腿堡',
        price: 18.5,
        quantity: 2,
        image: '/images/products/mcspicy.jpg',
        specifications: ['中辣']
      }
    ];
    
    wx.navigateTo({
      url: '/pages/order/order?storeId=1&storeName=麦当劳&orderType=delivery',
      success: () => {
        console.log('跳转到订单页面成功');
      },
      fail: (error) => {
        console.error('跳转到订单页面失败:', error);
        this.showToast('跳转失败，请重试');
      }
    });
  },

  // === 🎯 页面事件 ===
  onShareAppMessage() {
    return {
      title: '发现附近美食，一起来品尝吧！',
      path: '/pages/index/index',
      imageUrl: '/images/share-cover.jpg'
    };
  },

  onShareTimeline() {
    return {
      title: '发现附近美食，一起来品尝吧！',
      imageUrl: '/images/share-cover.jpg'
    };
  },

  // === 🎯 新增功能 ===
  async loadBanners() {
    try {
      const banners = await this.fetchBanners();
      this.setData({ banners });
      console.log('加载轮播广告成功:', banners.length);
    } catch (error) {
      console.error('加载轮播广告失败:', error);
      this.showError('加载轮播广告失败');
    }
  },

  async fetchBanners() {
    // 模拟API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        const banners = [
          {
            id: 1,
            image: '/images/banners/banner1.jpg',
            title: '新店开业优惠',
            link: '/pages/store-detail/store-detail?id=1001'
          },
          {
            id: 2,
            image: '/images/banners/banner2.jpg',
            title: '限时折扣活动',
            link: '/pages/store-detail/store-detail?id=1002'
          },
          {
            id: 3,
            image: '/images/banners/banner3.jpg',
            title: '美食节',
            link: '/pages/activity/activity?id=3001'
          }
        ];
        resolve(banners);
      }, 500);
    });
  },

  async loadCategories() {
    try {
      const categories = await this.fetchCategories();
      this.setData({ categories });
      console.log('加载分类成功:', categories.length);
    } catch (error) {
      console.error('加载分类失败:', error);
      this.setData({
        categories: []
      });
    }
  },
  
  async fetchCategories() {
    // 模拟API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        const categories = [
          {
            id: 'all',
            name: '全部',
            icon: '/images/default-avatar.png'
          },
          {
            id: 'fast_food',
            name: '快餐',
            icon: '/images/default-avatar.png'
          },
          {
            id: 'chinese',
            name: '中餐',
            icon: '/images/default-avatar.png'
          },
          {
            id: 'western',
            name: '西餐',
            icon: '/images/default-avatar.png'
          },
          {
            id: 'snack',
            name: '小吃',
            icon: '/images/default-avatar.png'
          },
          {
            id: 'dessert',
            name: '甜点',
            icon: '/images/default-avatar.png'
          },
          {
            id: 'drinks',
            name: '饮品',
            icon: '/images/default-avatar.png'
          }
        ];
        resolve(categories);
      }, 500);
    });
  },

  async loadRecommendedFood() {
    try {
      const recommendedFood = await this.fetchRecommendedFood();
      this.setData({ recommendedFood });
      console.log('加载推荐美食成功:', recommendedFood.length);
    } catch (error) {
      console.error('加载推荐美食失败:', error);
      this.setData({
        recommendedFood: []
      });
    }
  },
  
  async fetchRecommendedFood() {
    // 模拟API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        const recommendedFood = [
          {
            id: 101,
            name: '招牌鲜虾炒饭',
            price: 32.00,
            originalPrice: 38.00,
            image: '/images/default-product.png',
            storeName: '海鲜大咖'
          },
          {
            id: 102,
            name: '黑椒牛排意面',
            price: 48.00,
            originalPrice: null,
            image: '/images/default-product.png',
            storeName: '意式餐厅'
          },
          {
            id: 103,
            name: '松露蘑菇披萨',
            price: 68.00,
            originalPrice: 88.00,
            image: '/images/default-product.png',
            storeName: '披萨工坊'
          },
          {
            id: 104,
            name: '水果茶',
            price: 18.00,
            originalPrice: null,
            image: '/images/default-product.png',
            storeName: '果然好茶'
          },
          {
            id: 105,
            name: '彩虹蛋糕',
            price: 26.00,
            originalPrice: 32.00,
            image: '/images/default-product.png',
            storeName: '甜心烘焙'
          }
        ];
        resolve(recommendedFood);
      }, 600);
    });
  },
  
  // 选择美食分类
  selectCategory(e) {
    const categoryId = e.currentTarget.dataset.id;
    console.log('选择分类:', categoryId);
    
    // 设置当前选中的分类
    this.setData({
      selectedCategory: categoryId
    });
    
    // 根据分类筛选商家
    this.filterStoresByCategory(categoryId);
  },
  
  // 根据分类筛选商家
  async filterStoresByCategory(categoryId) {
    try {
      this.setData({ loading: true });
      
      // 如果选择"全部"分类，则显示所有商家
      if (categoryId === 'all') {
        await this.loadStores();
      } else {
        // 模拟根据分类筛选商家
        const filteredStores = await this.getStoresByCategory(categoryId);
        
        this.setData({
          stores: filteredStores,
          loading: false
        });
      }
      
    } catch (error) {
      console.error('筛选商家失败:', error);
      this.showError('筛选失败，请重试');
      this.setData({ loading: false });
    }
  },
  
  // 根据分类获取商家
  async getStoresByCategory(categoryId) {
    // 模拟API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        const allStores = this.getMockStores();
        
        // 模拟分类筛选逻辑
        let filtered = allStores;
        
        switch (categoryId) {
          case 'fast_food':
            filtered = allStores.filter(store => 
              store.tags.some(tag => ['快餐', '汉堡', '炸鸡'].includes(tag))
            );
            break;
          case 'chinese':
            filtered = allStores.filter(store => 
              store.tags.some(tag => ['中餐', '川菜', '粤菜', '火锅'].includes(tag))
            );
            break;
          case 'western':
            filtered = allStores.filter(store => 
              store.tags.some(tag => ['西餐', '意式', '美式', '披萨'].includes(tag))
            );
            break;
          case 'snack':
            filtered = allStores.filter(store => 
              store.tags.some(tag => ['小吃', '零食', '烧烤'].includes(tag))
            );
            break;
          case 'dessert':
            filtered = allStores.filter(store => 
              store.tags.some(tag => ['甜点', '蛋糕', '冰淇淋'].includes(tag))
            );
            break;
          case 'drinks':
            filtered = allStores.filter(store => 
              store.tags.some(tag => ['饮品', '咖啡', '奶茶', '酒水'].includes(tag))
            );
            break;
          default:
            filtered = allStores;
        }
        
        resolve(filtered);
      }, 800);
    });
  },
  
  // 轮播广告点击
  onBannerTap(e) {
    const bannerId = e.currentTarget.dataset.id;
    console.log('点击轮播广告:', bannerId);
    
    // 获取对应的轮播广告信息
    const banner = this.data.banners.find(item => item.id === bannerId);
    
    if (banner && banner.link) {
      // 跳转到对应页面
      wx.navigateTo({
        url: banner.link,
        fail: (error) => {
          console.error('跳转失败:', error);
          this.showToast('页面跳转失败');
        }
      });
    }
  },
  
  // 跳转到食品详情
  goToFoodDetail(e) {
    const foodId = e.currentTarget.dataset.id;
    console.log('跳转到食品详情:', foodId);
    
    wx.navigateTo({
      url: `/pages/food-detail/food-detail?id=${foodId}`,
      fail: (error) => {
        console.error('跳转失败:', error);
        this.showToast('页面跳转失败，详情页开发中...');
      }
    });
  }
}) 